package com.bdqn.tour.servlet.comments;

import com.alibaba.fastjson.JSON;
import com.bdqn.tour.util.CommentService;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/deleteComment")
public class DeleteCommentServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        String commentIdStr = request.getParameter("comment-id");

        if (commentIdStr != null) {
            try {
                int commentId = Integer.parseInt(commentIdStr);
                boolean success = new CommentService().deleteComment(commentId);
                PrintWriter out = response.getWriter();
                Map<String, Object> map = new HashMap<>();
                if (success) {
                    map.put("success", true);
                    map.put("msg", "删除成功");

                } else {

                    map.put("success", false);
                    map.put("msg", "删除失败");
                }
                String json = JSON.toJSONString(map);
                out.print(json);
                out.flush();
                out.close();
            } catch (NumberFormatException e) {
                response.setContentType("application/json");
                PrintWriter out = response.getWriter();
                out.print("{\"success\": false}");
                out.flush();
            }
        }
    }
}